package gui.calendarview;

import gui.CalendarWindow;

import java.util.ArrayList;
import java.util.Date;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListSelectionModel;

import no.ntnu.fp.model.ActivityModel;
import no.ntnu.fp.model.CalendarModel;
import no.ntnu.fp.model.Person;
import no.ntnu.fp.swingutil.CalendarTools;

public class DayListComponent extends JList {

	private static final long serialVersionUID = 1L;
	protected DefaultListModel dataModel;
	protected CalendarTools ct;
	protected Date day;
	private boolean displayHourOfDay;
	private Person user;

	public DayListComponent(Date day, boolean displayHourOfDay, Person user) {
		super();
		this.user = user;
		setDisplayHourOfDay(displayHourOfDay);
		ct = new CalendarTools();
		dataModel = new DefaultListModel();
		setModel(dataModel);
		setCellRenderer(new DayListCellRenderer());
		setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		setBackground(CalendarWindow.APPLICATION_BACKGROUND);
		setDay(day);
	}
	
	public Date getDay() {
		return day;
	}

	public void setDay(Date day) {
		this.day = ct.getDate(ct.getYear(day), ct.getMonth(day), ct.getDayOfMonth(day));
		updateList();
	}
	
	public void setDisplayHourOfDay(boolean displayHourOfDay) {
		this.displayHourOfDay = displayHourOfDay;
	}
	
	@Override
	protected void fireSelectionValueChanged(int firstIndex, int lastIndex, boolean isAdjusting) {
		if (!isSelectionEmpty() ) 
			super.fireSelectionValueChanged(firstIndex, lastIndex, isAdjusting);
	}

	public void updateList() {
		if ( !dataModel.isEmpty() )
			dataModel.clear();
		CalendarModel calendarModel = new CalendarModel(user);
		ArrayList<ActivityModel> activityModels = calendarModel.getScheduleDay(day);
		Date timeOfDay = day;
		for (int i = 0; i < 24; i++) {
			Date nextHour = ct.getNextHour(timeOfDay);
			ListElement e = new ListElement(timeOfDay,null,displayHourOfDay);
			for (int j = 0; j < activityModels.size(); j++) {
				ActivityModel model1 = activityModels.get(j);
				if ( model1.collides(timeOfDay,nextHour) )
					e.setModel(model1);
			}
			dataModel.addElement(e);
			timeOfDay = nextHour;
		}
	}
	
	public String toString() {
		return day.toString();
	}

}
